//
//  LBReactBridge.m
//  LBReact
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBBridge.h"
#import <LBFoundation/LBFoundation.h>

@interface LBBridgeModuleInfo()
@end
@implementation LBBridgeModuleInfo
@end

@interface LBBridge ()

@property (nonatomic, strong) NSMutableArray<LBBridgeModuleInfo *> *modules;
@property (nonatomic, strong) NSMutableArray<NSString *> *compnents;

@end

@implementation LBBridge

- (void)dealloc {
    
}

- (instancetype)initWithDelegate:(id<RCTBridgeDelegate>)delegate
                   launchOptions:(NSDictionary *)launchOptions {
    if (self = [super initWithDelegate:delegate
                         launchOptions:launchOptions]) {
        _state = LBBridgeUsedStateInit;
        _usedCount = 0;
    }
    return self;
}

- (BOOL)isContainModule:(NSString *)module {
    return [self.modules containsObject:module];
}

- (NSInteger)indexForModule:(NSString *)module {
    LBBridgeModuleInfo *moduleInfo = [[[self.modules copy] filteredArrayUsingPredicate:
                                       [NSPredicate predicateWithFormat:@"name == %@", module]] firstObject];
    return moduleInfo ? moduleInfo.index : -1;
}

- (NSURL *)URLForAsset:(NSURL *)mainFolderURL {
    NSFileManager *mananger = [NSFileManager defaultManager];
    if ([mananger fileExistsAtPath:[mainFolderURL absoluteString]]) {
        return mainFolderURL;
    }
    __block NSURL *URL = mainFolderURL;
    NSString *mainBundleFolder = [[[[self.bundleURL filePathURL] absoluteString] stringByDeletingLastPathComponent] removeFileSystem];
    NSString *assetFilePath = [[mainFolderURL absoluteString] removeFileSystem];
    [self.modules enumerateObjectsUsingBlock:^(LBBridgeModuleInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *filePath = [assetFilePath stringByReplacingOccurrencesOfString:mainBundleFolder
                                                                      withString:obj.folderPath];
        NSString *folderPath = [filePath stringByDeletingLastPathComponent];
        NSString *fileName = filePath.lastPathComponent;
        NSString *extension = filePath.pathExtension;
        NSString *pureFileName = [fileName stringByDeletingPathExtension];
        
        BOOL isExist = NO;
        
        if ([extension caseInsensitiveCompare:@"png"] == NSOrderedSame) {
            pureFileName = [pureFileName stringByReplacingOccurrencesOfString:@"@3x"
                                                           withString:@""];
            pureFileName = [pureFileName stringByReplacingOccurrencesOfString:@"@2x"
                                                           withString:@""];
            CGFloat scale = [UIScreen mainScreen].scale;
            filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@%@x.%@", pureFileName, scale == 2 ? @2 : @3, extension]];
            isExist = [mananger fileExistsAtPath:filePath];
            if (!isExist) {
                filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@%@x.%@", pureFileName, scale == 2 ? @3 : @2, extension]];
                isExist = [mananger fileExistsAtPath:filePath];
            }
            if (!isExist) {
                filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", pureFileName, extension]];
                isExist = [mananger fileExistsAtPath:filePath];
            }
        } else {
            isExist = [mananger fileExistsAtPath:filePath];
        }
        
        if (isExist) {
            URL = [NSURL fileURLWithPath:filePath];
            *stop = YES;
        }
        
    }];
    return URL;
}

- (BOOL)isContainCompnent:(NSString *)compnent {
    return [self.compnents containsObject:compnent];
}

- (void)addModule:(NSString *)module
            index:(NSUInteger)index {
    NSAssert([self indexForModule:module] < 0, @"一个bridge中同一个module只能存在一个版本，请检查逻辑");
    LBBridgeModuleInfo *moduleInfo = [[LBBridgeModuleInfo alloc] init];
    moduleInfo.name = module;
    moduleInfo.index = index;
    [self addModule:moduleInfo];
}

- (void)addModule:(LBBridgeModuleInfo *)moduleInfo {
    NSAssert([self indexForModule:moduleInfo.name] < 0, @"一个bridge中同一个module只能存在一个版本，请检查逻辑");
    [self.modules addObject:moduleInfo];
}

- (void)addCompnent:(NSString *)compnent {
    if (compnent.length > 0) {
        [self.compnents addObject:compnent];
    }
}

- (void)increase {
    self.usedCount++;
}

- (void)decrease {
    if (self.usedCount > 0) {
        self.usedCount--;
    }
}

- (NSMutableArray<LBBridgeModuleInfo *> *)modules {
    if (_modules) {
        return _modules;
    }
    
    _modules = [@[] mutableCopy];
    return _modules;
}

- (NSMutableArray<NSString *> *)compnents {
    if (_compnents) {
        return _compnents;
    }
    
    _compnents = [@[] mutableCopy];
    return _compnents;
}

@end
